import {ElMessage} from "element-plus";
import router from "@/router/index.js";
import {localSecretStorage, sessionSecretStorage} from "@/utils/ls.js";

export default function errorHandler(error) {
    const config = error.config || {};
    const message = error.response?.data?.message ||
        error.response?.data?.msg ||
        error.response?.statusText ||
        config.timeoutErrorMessage ||
        error.response?.data?.data ||
        '';

    let errorMsg = '未知错误，请稍后重试';

    if (!error.response) {
        console.log(error)
        // 网络错误（断网、请求未发出）
        errorMsg = '网络连接失败，请检查网络';
    } else {
        switch (error.response.status) {
            case 400:
                errorMsg = '请求参数错误';
                break;
            case 401:
                errorMsg = '未授权，请重新登录';
                // 可触发登出
                localStorage.removeItem('token');
                router.push('/login').then(() => {
                    localSecretStorage.removeItem("token")
                    sessionSecretStorage.removeItem("token")
                });
                break;
            case 403:
                errorMsg = '拒绝访问';
                localSecretStorage.removeItem("token")
                sessionSecretStorage.removeItem("token")
                router.push("/login").then((r) => {
                    ElMessage.error(error.response.statusText);

                });
                break;
            case 404:
                errorMsg = '请求地址不存在';
                break;
            case 500:
                errorMsg = '服务器内部错误';
                break;
            case 502:
                errorMsg = '网关错误';
                break;
            case 503:
                errorMsg = '服务不可用';
                break;
            case 504:
                errorMsg = '网关超时';
                break;
            default:
                errorMsg = message || `连接错误 ${error.response.status}`;
        }
    }

    ElMessage.error(errorMsg);

    // 仍然抛出错误，以便调用方处理
    return Promise.reject(error);
}